/*
 * Copyright (C) 2011 Lavettacn Xiao (lavettacn@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lavettacn.android.app.sociallessness.account;

import android.content.Context;
import android.content.pm.ProviderInfo;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

import com.lavettacn.android.app.sociallessness.data.DataContentProvider;

public final class AccountContentProvider extends DataContentProvider {
    public static final String AUTHORITY =
            "com.lavettacn.android.app.sociallessness.account.AccountContentProvider";
    public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY);
    public static final Uri ACCOUNT_URI = Uri.withAppendedPath(BASE_URI, "account");

    private static final String TAG = "AccountContentProvider";
    private static final String ACCOUNT_TYPE = "com.lavettacn.android.app.sociallessness.account";

    private final AccountTable mAccountTable = new AccountTable();

    @Override
    public void attachInfo(Context context, ProviderInfo info) {
        super.attachInfo(context, info);
        setDatabase(new Database(context, Database.DATABASE_NAME));

        addMapping(AUTHORITY, mAccountTable.getTableName(), ACCOUNT_TYPE, mAccountTable);
    }

    public void addAccount(String name, String type, String token, long expires) {
        AccountTable account = new AccountTable();
        account.mAccountName = name;
        account.mServiceType = type;
        account.mAccessToken = token;
        account.mAccessTokenExpires = expires;
        account.insertOrReplace(getDatabase().getWritableDatabase());
    }

    private final class Database extends SQLiteOpenHelper {
        public static final String DATABASE_NAME = "account.db";
        public static final int DATABASE_VERSION = 1;

        public Database(Context context, String name) {
            super(context, name, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            mAccountTable.createTable(db);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            mAccountTable.dropTable(db);
            onCreate(db);
        }
    }

}
